<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="list" :props="defaultProps" default-expand-all>
        <template #default="{data}">
          <el-row type="flex" justify="space-between" align="middle" style="width: 100%;">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>

              <!-- $event 实参 表示类型 -->
              <el-dropdown @command="operateDept($event,data.id)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>

                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>

                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>

                  <el-dropdown-item command="del">删除</el-dropdown-item>

                </el-dropdown-menu>

              </el-dropdown>

            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <addDept :id="pid" ref="dialog" :show-dialog.sync="showDialog" @updateList="getDepaetmentList()" />
  </div>

</template>
<script>
import { delDepartmentAPI, getDepaetmentListAPI } from '@/api/department'
import { translateListToTreeData } from '@/utils'
import addDept from './components/add-dept.vue'

export default {
  name: 'Department',
  components: {
    addDept
  },
  data() {
    return {
      showDialog: false,
      list: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      pid: null
    }
  },
  created() {
    this.getDepaetmentList()
  },
  methods: {
    async getDepaetmentList() {
      const res = await getDepaetmentListAPI()
      this.list = translateListToTreeData(res, 0)
    },
    async operateDept(type, id) {
      console.log(type)

      if (type === 'add') {
        this.showDialog = true
        this.pid = id
      } else if (type === 'edit') {
        this.pid = id
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs.dialog.getDepartmentDetail()
        })
      } else if (type === 'del') {
        this.$confirm('您确认要删除该部门吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delDepartmentAPI(id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getDepaetmentList()
        })
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 80px;
  display: inline-block;
  margin: 10px;
}
</style>
